package com.derek.omshopping.helper;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.derek.omshopping.bean.mine.LoginDatabaseEntity;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * 作者：ThinkPad on 2016/10/20 14:45
 * 邮箱：212740182@qq.com
 */
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
    public static final String TABLE_NAME = "sqlite-test.db";
    public static final int TABLE_VERSION = 1;
    private Map<String, Dao> daos = new HashMap<>();

    // 使用单例模式创建对象
    private static DatabaseHelper instance;
    public synchronized static DatabaseHelper getInstance(Context context){
        if (instance == null){
            synchronized (Object.class){
                if (instance == null){
                    instance = new DatabaseHelper(context);
                }
            }
        }
        return instance;
    }

    private DatabaseHelper(Context context) {
        super(context, TABLE_NAME, null, TABLE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
        try {
            // 创建数据库
            TableUtils.createTable(connectionSource, LoginDatabaseEntity.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int i, int i1) {
        // 更新数据库
        try {
            TableUtils.dropTable(connectionSource, LoginDatabaseEntity.class, true);
            onCreate(sqLiteDatabase, connectionSource);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public synchronized Dao getDao(Class clazz)throws SQLException{
        Dao dao = null;
        // 获取传进来的对象名
        String className = clazz.getSimpleName();
        // 判断daos是否存储了该对象表
        if (daos.containsKey(className)){
            dao = daos.get(className);
        }
        if (dao == null){

            daos.put(className, dao);
            dao = super.getDao(clazz);
        }
        return dao;
    }

    /**
     *  释放资源
     */
    @Override
    public void close() {
        super.close();
        for (String key : daos.keySet()){
            Dao dao = daos.get(key);
            dao = null;
        }
    }}
